#!/usr/bin/env python

import os
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import run_wsgi_app

from django.utils import simplejson



class Company(db.Model):

  company_name = db.StringProperty(multiline=False)
  primary_user = db.UserProperty()
  address = db.StringProperty(multiline=True)
  postcode = db.StringProperty(multiline=False)
  country_code = db.StringProperty(multiline=False)
  telephone_number = db.StringProperty(multiline=False)
  fax_number = db.StringProperty(multiline=False)
  registered_company_number = db.StringProperty(multiline=False)
  vat_number = db.StringProperty(multiline=False)
  last_updated_date = db.DateTimeProperty(auto_now_add=True)
  created_date = db.DateTimeProperty(auto_now_add=True)


class DebugHandler(webapp.RequestHandler):

  def get(self):

    companies = db.GqlQuery("SELECT * FROM Company LIMIT 1")

    for company in companies:
      self.response.out.write(company.company_name)



class RPCHandler(webapp.RequestHandler):

  """ Allows the functions defined in the RPCMethods class to be RPCed."""

  def __init__(self):
    webapp.RequestHandler.__init__(self)
    self.methods = RPCMethods()


  def get(self):

    func = None

    action = self.request.get('action')
    if action:
      if action[0] == '_':
        self.error(403) # access denied
        return
      else:
        func = getattr(self.methods, action, None)
   
    if not func:
      self.error(404) # file not found
      return
     
    args = ()
    while True:
      key = 'arg%d' % len(args)
      val = self.request.get(key)
      if val:
        args += (simplejson.loads(val),)
      else:
        break
    result = func(*args)
    self.response.out.write(simplejson.dumps(result))


  def post(self):
    func = None

    action = self.request.get('action')
    if action:
      if action[0] == '_':
        self.error(403) # access denied
        return
      else:
        func = getattr(self.methods, action, None)
   
    if not func:
      self.error(404) # file not found
      return
     
    args = ()
    while True:
      key = 'arg%d' % len(args)
      val = self.request.get(key)
      if val:
        args += (simplejson.loads(val),)
      else:
        break
    result = func(*args)
    self.response.out.write(simplejson.dumps(result))

    self.error(404) # under construction: access denied
    args = simplejson.loads(self.request.body)
    func, args = args[0], args[1:]
   
    if func[0] == '_':
      self.error(403) # access denied
      return
     
    func = getattr(self.methods, func, None)
    if not func:
      self.error(404) # file not found
      return

    result = func(*args)
    self.response.out.write(simplejson.dumps(result))


class RPCMethods:

  """ Defines the methods that can be RPCed.
  NOTE: Do not allow remote callers access to private/protected "_*" methods.
  """

  def Add(self, *args):
    # The JSON encoding may have encoded integers as strings.
    # Be sure to convert args to any mandatory type(s).
    ints = [int(arg) for arg in args]
    return sum(ints)


  def GetUsers(self, *args):

    user = users.get_current_user()

    r = []

    if user:
      r.append(user.nickname())
    else:
      r.append('&lt;unknown&gt;')

    return r


  def GetCompany(self, *args):

    companies = db.GqlQuery("SELECT * FROM Company LIMIT 1")

    for company in companies:
      return self.GetCompanyDict(company)


  def GetCompanyDict(self, company):
    d = dict()
    d['company_name'] = company.company_name
    d['primary_user'] = company.primary_user
    d['TODO'] = 'todo'
    return d


def main():

  application = webapp.WSGIApplication([
    ('/debug', DebugHandler),
    ('/rpc', RPCHandler),
  ], debug=True)

  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
